package com.sansan.ultrasound_handpad.fragment.home;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.qmuiteam.qmui.arch.QMUIFragmentActivity;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.QMUICollapsingTopBarLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.sansan.ultrasound_handpad.R;
import com.sansan.ultrasound_handpad.adaptor.brvah.PcbTaskPositionRecordAdapter;
import com.sansan.ultrasound_handpad.base.BaseFragment;
import com.sansan.ultrasound_handpad.base.MmkvManager;
import com.sansan.ultrasound_handpad.convertor.JsonConverter;
import com.sansan.ultrasound_handpad.entity.StaffEntity;
import com.sansan.ultrasound_handpad.fragment.KeyBoardUtil;
import com.sansan.ultrasound_handpad.fragment.SoftKeyBoardListener;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 员工页面
 */
public class UserFragment extends BaseFragment implements View.OnClickListener {

    private final static String TAG = UserFragment.class.getSimpleName();

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @BindView(R.id.homefragment_feeding_rButton)
    QMUIRoundButton mFeedingBtn;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.collapsing_topbar_layout)
    QMUICollapsingTopBarLayout mCollapsingTopBarLayout;
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;

    LinearLayoutManager mPagerLayoutManager;
    PcbTaskPositionRecordAdapter mAdapter;

    private Context context = null;
    private StaffEntity staffEntity = null;
    private int flag = 0;

//    public static void HideKeyboard(View v){
//        InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
//        if ( imm.isActive( ) ) {
//            imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 );
//        }
//    }
//
//    @Override
//    public void onCreate(Bundle savedInstanceState){
//        super.onCreate(savedInstanceState);
//        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        //HideKeyboard(mRecyclerView);
//
//    }

    /**
     * 创建首页视图
     * @return
     */
    @Override
    protected View onCreateView() {

        //getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
        btn.setOnClickListener(this);
        ButterKnife.bind(this, rootView);
        //初始化标题布局
        Log.d(TAG, "num-----------------------1: ");
        initTopBar();


        if (mFeedingBtn != null) {
            mFeedingBtn.setVisibility(View.GONE);
        }

        initAdapter();
        mPagerLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mPagerLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        //设置空白布局
        mAdapter.setEmptyView(getScanNumView());

        mCollapsingTopBarLayout.setScrimUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.i(TAG, "scrim: " + animation.getAnimatedValue());
            }
        });


        mCollapsingTopBarLayout.addOnOffsetUpdateListener(new QMUICollapsingTopBarLayout.OnOffsetUpdateListener() {
            @Override
            public void onOffsetChanged(QMUICollapsingTopBarLayout layout, int offset, float expandFraction) {
                Log.i(TAG, "offset = " + offset + "; expandFraction = " + expandFraction);
            }
        });


        return rootView;

    }

    /**
     * 初始化头顶布局
     */
    private void initTopBar() {
        mCollapsingTopBarLayout.setTitle("扫描工号");

        mTopBar.addLeftImageButton(R.mipmap.icon_topbar_about, R.id.topbar_right_about_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 showIpDialog();
            }
        });

    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new PcbTaskPositionRecordAdapter();
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    if (view.getId() == R.id.pcb_taskposition_record_rv_item_cb) {
                        Toast.makeText(getActivity(), "勾选了第" + position + "个", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }


    /**
     * 带输入框的对话框(填写接口调用的ip和端口)
     */
    private void showIpDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        builder.setTitle("设置IP地址")
                .setSkinManager(QMUISkinManager.defaultInstance(getContext()))
                .setPlaceholder("在此输入您的IP")
                .setDefaultText(obtainIP())
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if (MmkvManager.getInstance().getMMKV().encode("PAD_IP", builder.getEditText().getText().toString())) {
                            Toast.makeText(getActivity(), "设置成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), "设置失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    /**
     * 获取IP地址和端口
     */
    private String obtainIP() {
        return MmkvManager.getInstance().getMMKV().decodeString("PAD_IP", "http://192.168.10.20:8755/");
        //return MmkvManager.getInstance().getMMKV().decodeString("PAD_IP", "http://192.168.10.20:8755/");
    }

    /**
     * 扫码广播
     */
    /*接收扫码器传回来的扫码数据*/
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        //监听软件盘是否弹起
//        private void onKeyBoardListener() {
//            SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
//                @Override
//                public void keyBoardShow(int height) {
//                    Log.e("软键盘", "键盘显示 高度" + height);
//                }
//
//                @Override
//                public void keyBoardHide(int height) {
//                    Log.e("软键盘", "键盘隐藏 高度" + height);
//                }
//            });
//        }



        @Override
        public void onReceive(Context context, Intent intent) {
            /*扫描数据*/
            byte[] scanData = intent.getByteArrayExtra("barocode");
            /*数据长度*/
            int dataLen = intent.getIntExtra("length", 0);
            /*数据类型*/
            byte dataTyp = intent.getByteExtra("barcodeType", (byte)0);
            /*条码字符串*/
            String barcodeStr = new String(scanData, 0, dataLen);
            Log.d(TAG, "BroadcastReceiver: " + barcodeStr);
            /**
             * 获取工号去查询
             */
            if (!TextUtils.isEmpty(barcodeStr)) {
                if (flag == 0) {  //获取工号
                    /*if (barcodeStr.length() == 5 || barcodeStr.length() == 6){
                        Toast.makeText(getActivity(),"扫码成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(getActivity(),"请扫描正确的员工二维码",Toast.LENGTH_SHORT).show();
                    }
                    if ((barcodeStr.length() != 5 && barcodeStr.charAt(0) != 'S') || (!barcodeStr.equals("123456"))){
                        Toast.makeText(getActivity(),"请扫描正确的员工二维码",Toast.LENGTH_SHORT).show();
                    }
                    obtainUsrMsg(barcodeStr);*/

                    String reg = "^S[0-9]{4,5}$"; //用正则表达式匹配员工工号 规则;S开头,后4/5位为数字
                    System.out.println(barcodeStr.matches(reg));

                    if (barcodeStr.matches(reg)){
                        obtainUsrMsg(barcodeStr);
                    } else {
                        ToastUtil.showToast(getActivity(),"员工二维码格式错误");
                        //Toast.makeText(getActivity(),"请扫描正确的员工二维码",Toast.LENGTH_LONG).show();
//                        Toast toast = Toast.makeText(getActivity(), "员工二维码格式错误", Toast.LENGTH_SHORT);
//                        LinearLayout layout = (LinearLayout) toast.getView();
//                        TextView tv = (TextView) layout.getChildAt(0);
//                        tv.setTextSize(22);
                        //toast.setGravity(Gravity.CENTER, 0, 0);
                        //toast.setMargin(500,500);
//                        toast.show();
                    }
                }
            }
        }
    };

    /**
     * 扫描工号的界面
     */
    private View getScanNumView() {
        flag = 0;

        if (mCollapsingTopBarLayout != null) {
            mCollapsingTopBarLayout.setTitle("扫描工号");
        }

        View errorView = getLayoutInflater().inflate(R.layout.scanning_worknum_layout, mRecyclerView, false);
        errorView.findViewById(R.id.scanning_worknum_rButton).setOnClickListener(v -> {
            //Toast.makeText(getActivity(), "点击了员工扫码按钮", Toast.LENGTH_SHORT).show();
            /*try {
                mediaPlayer = MediaPlayer.create(context,R.raw.finish);
                mediaPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            //调用登录接口
            loginWebPage();
        });

        return errorView;
    }

    /**
     * 登录接口
     */
    public void loginWebPage() {
        if (mCollapsingTopBarLayout != null) {
            if (staffEntity == null){
                getScanNumView();
            }else {
                mCollapsingTopBarLayout.setTitle("欢迎:" + staffEntity.getNickname());
            }
        }

        Kalle
                .post(obtainIP() + "login")
                .param("username", "admin")
                .param("password", "123456")
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        if (response.isSucceed()) {
                            //登录成功切回页面
                            if (mAdapter != null) {
                                mAdapter.setEmptyView(getScanNumView());
                                getScanCodeView();
                                //mCollapsingTopBarLayout.setTitle("欢迎"+staffEntity.getNickname());
                                //getScanCodeView();
                                startFragment(new ProcessFragment());
                                //mAdapter.setEmptyView(R.id.scanning_code_obtainrecord_rButton);

                            }
                        }
                        Log.d(TAG, "onResponse: " + response.succeed());
                    }
                });
    }

    /**
     * 扫描获取程序信息界面
     */
    private View getScanCodeView() {

        if (staffEntity == null){
            getScanNumView();
        }

        if (mCollapsingTopBarLayout != null) {
            mCollapsingTopBarLayout.setTitle("欢迎:" + (staffEntity == null ? "" : staffEntity.getNickname()));
        }

       View errorView = getLayoutInflater().inflate(R.layout.scanning_code_obtainrecrd_layout, mRecyclerView, false);

       /*  errorView.findViewById(R.id.scanning_code_obtainrecord_rButton).setOnClickListener(v -> {
            Toast.makeText(getActivity(), "点击了程序扫码按钮", Toast.LENGTH_SHORT).show();
            //getScanCodeView();
            //Toast.makeText(getActivity(), "扫码获取程序信息界面", Toast.LENGTH_SHORT).show();
            //获取程序信息
            //obtainPcbTaskPostionRecord(null, null, null);
        });
        */
        return errorView;
    }

    @Override
    public void onClick(View v) {
//        switch (v.getId()){
//            case R.id.homefragment_feeding_rButton:
//                break;
//            default:
//                break;
//        }
    }

    /**
     * 获取工号
     */
    private void obtainUsrMsg(String num) {
        Kalle
                .get(obtainIP() + "PcbTaskPositionRecord/getUserInfoByCard/" + num)
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<StaffEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<StaffEntity, String> response) {

                        if (mAdapter != null && response.isSucceed()) {
                            if (!(response.succeed() instanceof StaffEntity)) {
                                Log.d(TAG, "onResponse: 不是StaffEntity类型" + response.succeed());
                                return;
                            }
                            staffEntity = response.succeed();

                            ProcessFragment fragment = new ProcessFragment();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("UserMsg", staffEntity);
                            fragment.setArguments(bundle);
                            startFragment(fragment);
                        }
                    }
                });
    }



    @Override
    public void onResume() {
        super.onResume();

        if (getActivity() == null) {
            return;
        }
        /*注册扫描器广播*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("urovo.rcv.message");
        getActivity().registerReceiver(this.mScanReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (getActivity() == null) {
            return;
        }
        /*注销扫描器广播*/
        getActivity().unregisterReceiver(this.mScanReceiver);
    }


    // 关闭键盘
    public void closeKeyboard(Activity context) {
        if (context == null) {
            return;
        }
        final View v = context.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

//    new Thread(){
//                @Override
//                public void run() {
//                    Instrumentation instrumentation = new Instrumentation();
//                    instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
//                }
//            }.start();

}
